package com.example.scenictourback.controller;

import com.example.scenictourback.common.Result;
import com.example.scenictourback.dto.OrderDTO;
import com.example.scenictourback.entity.Order;
import com.example.scenictourback.entity.User;
import com.example.scenictourback.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 创建订单
     */
    @PostMapping("/create")
    public Result<?> createOrder(@RequestBody Map<String, Object> orderData) {
        try {
            // 构建Order实体
            Order order = new Order();
            
            // 设置用户
            Map<String, Object> userMap = (Map<String, Object>) orderData.get("user");
            Integer userId = ((Number) userMap.get("id")).intValue();
            User user = new User();
            user.setId(userId);
            order.setUser(user);
            
            // 设置产品ID和类型
            Integer productId = ((Number) orderData.get("productId")).intValue();
            Integer type = ((Number) orderData.get("type")).intValue();
            order.setProductId(productId);
            order.setType(type);
            
            // 设置数量和金额
            Integer quantity = ((Number) orderData.get("quantity")).intValue();
            BigDecimal totalAmount = new BigDecimal(orderData.get("totalAmount").toString());
            order.setQuantity(quantity);
            order.setTotalAmount(totalAmount);
            
            // 处理日期
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date bookDate = dateFormat.parse(orderData.get("bookDate").toString());
            Date useDate = dateFormat.parse(orderData.get("useDate").toString());
            order.setBookDate(bookDate);
            order.setUseDate(useDate);
            
            // 设置状态
            Integer status = ((Number) orderData.get("status")).intValue();
            order.setStatus(status);
            
            // orderNo会在服务层自动生成
            
            // 调用服务创建订单
            OrderDTO createdOrder = orderService.createOrder(order);
            return Result.success("创建订单成功", createdOrder);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有订单（管理员权限）
     */
    @GetMapping("/all")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> listAllOrders(
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) Integer status) {
        List<OrderDTO> orders = orderService.listAllOrders(type, status);
        return Result.success(orders);
    }
    
    /**
     * 获取用户的订单列表
     */
    @GetMapping("/user/{userId}")
    public Result<?> listUserOrders(
            @PathVariable Integer userId,
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) Integer status) {
        try {
            List<OrderDTO> orders = orderService.listUserOrders(userId, type, status);
            return Result.success(orders);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据订单号获取订单详情
     */
    @GetMapping("/detail")
    public Result<?> getOrderByOrderNo(@RequestParam String orderNo) {
        OrderDTO order = orderService.getOrderByOrderNo(orderNo);
        return Result.success(order);
    }
    
    /**
     * 根据ID获取订单详情
     */
    @GetMapping("/{id}")
    public Result<?> getOrderById(@PathVariable Integer id) {
        OrderDTO order = orderService.getOrderById(id);
        return Result.success(order);
    }
    
    /**
     * 更新订单状态（管理员权限）
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> updateOrderStatus(@PathVariable Integer id, @RequestBody Map<String, Integer> statusMap) {
        Integer status = statusMap.get("status");
        if (status == null) {
            return Result.error("缺少状态参数");
        }
        
        OrderDTO updatedOrder = orderService.updateOrderStatus(id, status);
        return Result.success("更新成功", updatedOrder);
    }
    
    /**
     * 取消订单
     */
    @PutMapping("/{id}/cancel")
    public Result<?> cancelOrder(@PathVariable Integer id) {
        OrderDTO canceledOrder = orderService.cancelOrder(id);
        return Result.success("取消成功", canceledOrder);
    }
    
    /**
     * 删除订单（管理员权限）
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> deleteOrder(@PathVariable Integer id) {
        orderService.deleteOrder(id);
        return Result.success("删除成功");
    }
    
    /**
     * 获取订单统计数据（管理员权限）
     */
    @GetMapping("/stats")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> getOrderStats() {
        Map<String, Object> stats = orderService.getOrderStats();
        return Result.success(stats);
    }
} 